#include "gameroom.h"
#include "gameselect.h"
#include<QIcon>
#include<QPainter>
#include<QPixmap>
#include<QIcon>
#include<QPushButton>
#include<QSound>
#include<QTimer>
#include<QPushButton>
#include<QSound>
#include<QMessageBox>
#include<QFile>
#include<QTextStream>

GameRoom::GameRoom(QWidget *parent) : QWidget(parent)
{
    //窗口大小
    this->setFixedSize(1000,900);
    //设置窗口图标
    this->setWindowIcon(QIcon(":/Snake icon/snake.png"));
    //设置窗口标题
    this->setWindowTitle("游戏房间");

    //初始化蛇

    snakelist.push_back(QRectF(this->width()*0.5,this->height()*0.5,SnakeBodyWidth,SnakeBodyHeight));
    moveUp();
    moveUp();

    createnewfood();

    timer=new QTimer(this);

    connect(timer,&QTimer::timeout,[=](){
        int cnt=1;
        if(snakelist.front().intersects(foodRect))//说明相交了
        {
            createnewfood();
            cnt++;
        }
        while(cnt--)
        {
            switch (moveDirect) {
                case SnakeDirect::UP:
                    moveUp();
                    break;
                case SnakeDirect::DOWN:
                    moveDown();
                    break;
                case SnakeDirect::LEFT:
                    moveLeft();
                    break;
                case SnakeDirect::RIGHT:
                    moveRight();
                    break;
            }
        }
        snakelist.pop_back();//删除最后一个节点
        update();
    });

    //开始游戏和在暂停游戏
    QPushButton* startbutton=new QPushButton(this);
    QPushButton* stopbutton=new QPushButton(this);

    QFont font("微软雅黑",16);

    startbutton->move(825,160);
    startbutton->setFixedSize(150,50);
    startbutton->setText("开始游戏");
    startbutton->setFont(font);

    stopbutton->move(825,260);
    stopbutton->setFixedSize(150,50);
    stopbutton->setText("暂停游戏");
    stopbutton->setFont(font);

    connect(startbutton,&QPushButton::clicked,[=](){
        isGameStart=true;
        timer->start(movespeed);
        sound=new QSound(":/Snake icon/snakemove.wav");
        sound->play();
        sound->setLoops(-1);
    });

    connect(stopbutton,&QPushButton::clicked,[=](){
        isGameStart=false;
        timer->stop();
        sound->stop();
    });


    //方向控制
    QPushButton* up=new QPushButton(this);
    QPushButton* down=new QPushButton(this);
    QPushButton* left=new QPushButton(this);
    QPushButton* right=new QPushButton(this);

    QPixmap pix(":/Snake icon/direct_down.png");
    down->move(869,510);
    down->setFixedSize(60,50);
    QIcon icon(pix);
    down->setIcon(icon);

    QPixmap pix1(":/Snake icon/direct_up.png");
    up->move(869,450);
    up->setFixedSize(60,50);
    QIcon icon1(pix1);
    up->setIcon(icon1);

    QPixmap pix2(":/Snake icon/direct_left.png");
    left->move(804,510);
    left->setFixedSize(60,50);
    QIcon icon2(pix2);
    left->setIcon(icon2);

    QPixmap pix3(":/Snake icon/direct_right.png");
    right->move(934,510);
    right->setFixedSize(60,50);
    QIcon icon3(pix3);
    right->setIcon(icon3);

    connect(up,&QPushButton::clicked,[=](){
        if(moveDirect!=SnakeDirect::DOWN)//并不支持掉头
        {
            moveDirect=SnakeDirect::UP;
        }
    });

    connect(down,&QPushButton::clicked,[=](){
        if(moveDirect!=SnakeDirect::UP)
        {
            moveDirect=SnakeDirect::DOWN;
        }
    });

    connect(left,&QPushButton::clicked,[=](){
        if(moveDirect!=SnakeDirect::RIGHT)
        {
            moveDirect=SnakeDirect::LEFT;
        }
    });

    connect(right,&QPushButton::clicked,[=](){
        if(moveDirect!=SnakeDirect::LEFT)
        {
            moveDirect=SnakeDirect::RIGHT;
        }
    });

    //退出按键

    QPushButton* exitbutton=new QPushButton(this);
    exitbutton->move(825,720);
    exitbutton->setFixedSize(150,50);
    exitbutton->setText("退出游戏");
    exitbutton->setFont(font);

    QMessageBox* msg=new QMessageBox(this);

    QPushButton* ok=new QPushButton("ok");
    QPushButton* cancel=new QPushButton("cancel");

    msg->addButton(ok,QMessageBox::AcceptRole);
    msg->addButton(cancel,QMessageBox::RejectRole);

    msg->setWindowTitle("退出游戏");
    msg->setText("确定要退出游戏吗？");

    connect(exitbutton,&QPushButton::clicked,[=](){
        msg->show();
        msg->exec();//事件轮询
        QSound::play(":/Snake icon/startgame_click.wav");

        Gameselect* select=new Gameselect;


        if(msg->clickedButton()==ok)
        {
            this->close();
            select->show();
        }
        else
        {
            msg->close();
        }
    });


}

void GameRoom::paintEvent(QPaintEvent *event)
{
    QPainter painter(this);

    QPixmap pixmap;//因为游戏页面是一部分游戏，一部分操作，所以这里并不直接初始化了QPixmap pixmap(":/Snake icon/select_background.png");

    pixmap.load(":/Snake icon/playing_background.png");
    painter.drawPixmap(0,0,800,this->height(),pixmap);

    pixmap.load(":/Snake icon/playing_background_right.png");
    painter.drawPixmap(800,0,200,this->height(),pixmap);

    //绘制蛇
    if(moveDirect==SnakeDirect::UP)
    {
        pixmap.load(":/Snake icon/snake_up.png");
    }
    else if(moveDirect==SnakeDirect::DOWN)
    {
        pixmap.load(":/Snake icon/snake_down.png");
    }
    else if(moveDirect==SnakeDirect::LEFT)
    {
        pixmap.load(":/Snake icon/snake_left.png");
    }
    else
    {
        pixmap.load(":/Snake icon/snake_right.png");
    }
    auto snakeHead=snakelist.front();
    painter.drawPixmap(snakeHead.x(),snakeHead.y(),snakeHead.width(),snakeHead.height(),pixmap);

    //绘制蛇身
    pixmap.load(":/Snake icon/snake_body.png");
    for(int i=1;i<snakelist.size()-1;i++)
    {
        auto node=snakelist.at(i);
        painter.drawPixmap(node.x(),node.y(),node.width(),node.height(),pixmap);
    }

    //绘制尾巴
    auto snakeTail=snakelist.back();
    painter.drawPixmap(snakeTail.x(),snakeTail.y(),snakeTail.width(),snakeTail.height(),pixmap);

    //绘制食物
    pixmap.load(":/Snake icon/food.png");
    painter.drawPixmap(foodRect.x(),foodRect.y(),foodRect.width(),foodRect.height(),pixmap);

    //绘制分数
    QPen pen;
    pen.setColor(Qt::black);
    painter.setPen(pen);
    QFont font("微软雅黑",20);
    painter.setFont(font);
    painter.drawText(this->width()*0.84,this->height()*0.1,QString("得分:%1").arg(snakelist.size()));

    //向文件当中写入历史分数
    int score=snakelist.size();
    QFile file("C:/text/sroce.txt.txt");
    if(file.open(QIODevice::WriteOnly|QIODevice::Text))
    {
        QTextStream out(&file);
        int num=score;
        out<<num;
        file.close();
    }



    //绘制游戏失败
    if(checkFail())
    {
        pen.setColor(Qt::red);
        painter.setPen(pen);
        QFont font("微软雅黑",50);
        painter.setFont(font);
        painter.drawText(this->width()*0.30,this->height()*0.5,QString("GAME OVER!"));
        timer->stop();
        QSound::play(":/Snake icon/returnsound.wav");
        sound->stop();
    }


}

void GameRoom::moveUp()
{
    QPointF leftTop;//左上角坐标
    QPointF rightBottom;//右下角坐标

    auto snakebody=snakelist.front();

    int headx=snakebody.x();
    int heady=snakebody.y();

    if(heady<0)//说明越界了
    {
        leftTop=QPointF(headx,this->height()-SnakeBodyHeight);
    }
    else
    {
        leftTop=QPointF(headx,heady-SnakeBodyHeight);
    }

    rightBottom=leftTop+QPointF(SnakeBodyWidth,SnakeBodyHeight);

    snakelist.push_front(QRectF(leftTop,rightBottom));                 //QPointF 用来表示单个点的坐标，主要用于指定二维空间中的位置。
                                                                       //QRectF 用来表示一个矩形区域，由左上角的点和矩形的宽高定义。
}

void GameRoom::moveDown()
{
    QPointF leftTop;//左上角坐标
    QPointF rightBottom;//右下角坐标

    auto snakebody=snakelist.front();

    int headx=snakebody.x();
    int heady=snakebody.y();

    if(heady>this->height())//说明越界了
    {
        leftTop=QPointF(headx,0);
    }
    else
    {                     //左下角
        leftTop=snakebody.bottomLeft();//
    }

    rightBottom=leftTop+QPointF(SnakeBodyWidth,SnakeBodyHeight);

    snakelist.push_front(QRectF(leftTop,rightBottom));
}

void GameRoom::moveLeft()
{
    QPointF leftTop;//左上角坐标
    QPointF rightBottom;//右下角坐标

    auto snakebody=snakelist.front();

    int headx=snakebody.x();
    int heady=snakebody.y();

    if(headx<0)
    {
        leftTop=QPointF(800-SnakeBodyWidth,heady);
    }
    else
    {
        leftTop=QPointF(headx-SnakeBodyWidth,heady);
    }

    rightBottom=leftTop+QPointF(SnakeBodyWidth,SnakeBodyHeight);

    snakelist.push_front(QRectF(leftTop,rightBottom));
}

void GameRoom::moveRight()
{
    QPointF leftTop;//左上角坐标
    QPointF rightBottom;//右下角坐标

    auto snakebody=snakelist.front();

    int headx=snakebody.x();
    int heady=snakebody.y();

    if(headx>760)//这里760是因为他会有越界的
    {
        leftTop=QPointF(0,heady);
    }
    else
    {
        leftTop=snakebody.topRight();
    }

    rightBottom=leftTop+QPointF(SnakeBodyWidth,SnakeBodyHeight);

    snakelist.push_front(QRectF(leftTop,rightBottom));
}

bool GameRoom::checkFail()
{
    for(int i=0;i<snakelist.size();i++)
    {
        for(int j=i+1;j<snakelist.size();j++)
        {
            if(snakelist.at(i)==snakelist.at(j))
            {
                return true;
            }
        }
    }
    return false;
}

void GameRoom::createnewfood()
{
    foodRect=QRectF(qrand()%(800/SnakeBodyWidth)*SnakeBodyWidth
                    ,qrand()%(this->height()/SnakeBodyHeight)*SnakeBodyHeight
                    ,SnakeBodyWidth,SnakeBodyHeight);
}
